package top.cardone.data.action;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import top.cardone.context.ApplicationContextHolder;
import top.cardone.core.util.action.Action0;
import top.cardone.core.util.action.Action1;
import top.cardone.core.util.func.Func1;

import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedDeque;

/**
 * Created by cardo on 2018/4/3 0003.
 */
@Log4j2
public class SaveListByGenerateListenerAction implements Action0, Action1<List<Map<String, Object>>> {
    @Setter
    private String saveListFuncBeanId;

    @Getter
    private Deque<Map<String, Object>> saveDeque = new ConcurrentLinkedDeque<>();

    @Override
    public void action(List<Map<String, Object>> saveList) {
        if (CollectionUtils.isEmpty(saveList)) {
            return;
        }

        saveList.forEach(m -> this.saveDeque.offerLast(m));
    }

    @Override
    public void action() {
        if (CollectionUtils.isEmpty(this.saveDeque)) {
            return;
        }

        Set<Object> newSaveSet = Sets.newHashSet();

        while (true) {
            Map<String, Object> save = this.saveDeque.pollFirst();

            if (save == null) {
                break;
            }

            newSaveSet.add(save);

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                log.error(e);
            }

            if (newSaveSet.size() > 100) {
                ApplicationContextHolder.action(Func1.class, func1 -> func1.func(Lists.newArrayList(newSaveSet)), saveListFuncBeanId);

                newSaveSet.clear();

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    log.error(e);
                }
            }
        }

        if (!newSaveSet.isEmpty()) {
            ApplicationContextHolder.action(Func1.class, func1 -> func1.func(Lists.newArrayList(newSaveSet)), saveListFuncBeanId);

            newSaveSet.clear();
        }
    }
}